package handler

import (
	"github.com/gin-gonic/gin"
	"piggy-charm/cache"
	"piggy-charm/moderl"
	"piggy-charm/pkg"
	"time"
)

func Loge(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "内容不能为空",
		})
		return
	}

	redis_key := "lo_id" + username
	errcache, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errcache >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次",
		})
		return
	}

	var user moderl.User
	err := moderl.DB.Where("user_name = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户ID不存在",
		})
		return
	}

	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errcache == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
